/**
 * [
  {
    "id": 1,
    "name": "部门1",
    "pid": 0,
    "children": [
      {
        "id": 2,
        "name": "部门2",
        "pid": 1,
        "children": []
      },
      {
        "id": 3,
        "name": "部门3",
        "pid": 1,
        "children": [
          {
            "id": 4,
            "name": "部门4",
            "pid": 3,
            "children": [
              {
                "id": 5,
                "name": "部门5",
                "pid": 4,
                "children": []
              }
            ]
          }
        ]
      }
    ]
  }
]

=>
[
  {id: 1, name: '部门1', pid: 0},
  {id: 2, name: '部门2', pid: 1},
  {id: 3, name: '部门3', pid: 1},
  {id: 4, name: '部门4', pid: 3},
  {id: 5, name: '部门5', pid: 4},
]
 * 
 */

const tree2list = (tree) => {
    let list = []
    let queue = [...tree]
  
    while (queue.length) {
      // 从前面开始取出节点
      const node = queue.shift()
      const children = node.children
  
      if (children.length) {
        queue.push(...children)
      }
      // 删除多余的children树形
      delete node.children
  
      list.push(node)
    }
  
    return list
  }
  

  const tree2listDeepth = (tree) => {
    let list = []
    let stack = [...tree]
  
    while (stack.length) {
      // 从前面开始取出节点
      const node = stack.pop()
      const children = node.children
  
      if (children?.length) {
        stack.push(...children)
      }
      // 删除多余的children树形
      delete node.children
  
      list.push(node)
    }
  
    return list
  }

  const data = [
    {
      "id": 1,
      "name": "部门1",
      "pid": 0,
      "children": [
        {
          "id": 2,
          "name": "部门2",
          "pid": 1,
          "children": []
        },
        {
          "id": 3,
          "name": "部门3",
          "pid": 1,
          "children": [
            {
              "id": 4,
              "name": "部门4",
              "pid": 3,
              "children": [
                {
                  "id": 5,
                  "name": "部门5",
                  "pid": 4,
                  "children": []
                }
              ]
            }
          ]
        }
      ]
    }
  ]
  const data2 = [
    {
      "id": 1,
      "name": "部门1",
      "pid": 0,
      "children": [
        {
          "id": 2,
          "name": "部门2",
          "pid": 1,
          "children": []
        },
        {
          "id": 3,
          "name": "部门3",
          "pid": 1,
          "children": [
            {
              "id": 4,
              "name": "部门4",
              "pid": 3,
              "children": [
                {
                  "id": 5,
                  "name": "部门5",
                  "pid": 4,
                  "children": []
                }
              ]
            }
          ]
        }
      ]
    }
  ]
  
  console.log(tree2list(data))
  console.log(tree2listDeepth(data2))